from flask import Blueprint, jsonify, request

from app.services import book_service

bp = Blueprint('books', __name__, url_prefix='/books')


@bp.route('/')
def get_book_list():
    books = book_service.get_all_books()

    return jsonify({'code': 1, 'message': '获取图书列表成功', 'data': books})


@bp.route('/<int:book_id>')
def get_book(book_id):
    book = book_service.get_book_by_id(book_id)

    return jsonify({'code': 1, 'message': '获取图书信息成功', 'data': book})


@bp.route('/', methods=['POST'])
def add_book():
    request_data = request.get_json()

    book_service.add_book(request_data)

    return jsonify({'code': 1, 'message': '添加图书成功'})


@bp.route('/<int:book_id>', methods=['DELETE'])
def delete_book(book_id):
    book_service.delete_book(book_id)

    return jsonify({'code': 1, 'message': '删除图书成功'})


@bp.route('/<int:book_id>', methods=['PUT'])
def update_book(book_id):
    request_data = request.get_json()

    print(f'要修改的图书信息：\n{request_data}')

    book_service.update_book(request_data)

    return jsonify({'code': 1, 'message': '修改图书信息成功'})
